﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework.Graphics;

namespace Tomahawk.Runtime.Rendering.Materials
{
    public sealed class SASPass
    {
        private SASScript script;
        public SASScript Script { get { return script; } }

        private SASTechnique sasTechnique;
        public SASTechnique Technique { get { return sasTechnique; } }

        private EffectPass pass;
        public EffectPass Pass { get { return pass; } }

        public string Name
        {
            get
            {
                if (pass == null) throw new SASUninitializedTechniqueException();
                return pass.Name;
            }
        }

        public bool Initialize(SASTechnique sasTechnique, EffectPass pass)
        {
            this.pass = pass;
            this.sasTechnique = sasTechnique;

            foreach (EffectAnnotation annotation in pass.Annotations)
            {
                if (string.Compare(annotation.Name, "SCRIPT", true) == 0)
                {
                    this.script = new SASScript(annotation.GetValueString());
                }
            }
            return true;
        }

        #region Rendering
        public bool DrawMesh(ref SASScript.Context context)
        {
            bool result = true;

            if (script != null)
            {
                result = script.Execute(ref context);
            }
            else
            {
                SASEffect effect = context.sasEffect;
                EffectPass pass = context.sasPass.Pass;
                GraphicsDevice device = context.device;

                pass.Begin();

                if (context.indexedVertices)
                {
                    device.DrawIndexedPrimitives(
                        context.primitiveType,
                        context.baseVertex,
                        0,
                        context.numVertices,
                        context.startIndex,
                        context.primitiveCount);
                }
                else
                {
                    device.DrawPrimitives(
                        context.primitiveType,
                        context.baseVertex,
                        context.primitiveCount);
                }

                pass.End();
            }

            return result;
        }
        #endregion
    }
}
